<template>
  <div class="app-container">
    <el-button type="primary" size="small" @click="handleAddAdmin">添加管理员</el-button>

    <el-table v-loading="adminForm.loading" :data="AdminList" style="width: 100%;margin-top:30px;" border>
      <el-table-column align="center" label="用户名" width="220">
        <template slot-scope="scope">{{ scope.row.name }}</template>
      </el-table-column>
      <el-table-column align="center" label="角色名称">
        <template slot-scope="scope">{{ getRoleName(scope.row.roles) }}</template>
      </el-table-column>
      <el-table-column align="header-center" label="创建时间" width="220">
        <template slot-scope="scope">{{ scope.row.created_at }}</template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope)">{{ $t('permission.editPermission') }}</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope)">{{ $t('permission.delete') }}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <br>
    <el-pagination
      v-show="adminForm.total>0 && adminForm.total > adminForm.limit"
      background
      layout="total, prev, pager, next, sizes"
      :page-sizes="adminForm.page_size"
      :current-page.sync="adminForm.page"
      :page-size="adminForm.limit"
      :total="adminForm.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'编辑管理员':'新增管理员'">
      <el-form ref="ruleForm" :rules="rules" :model="adminForm" label-width="80px" label-position="left">
        <el-form-item label="用户名" prop="name">
          <el-input v-model="adminForm.name" placeholder="用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="adminForm.password" type="password" placeholder="密码" />
        </el-form-item>
        <el-form-item label="确认密码" prop="password_confirmation">
          <el-input v-model="adminForm.password_confirmation" type="password" placeholder="确认密码" />
          <br>
          <span v-show="dialogType==='edit'">密码不填写代表不重设密码！</span>
        </el-form-item>
        <el-form-item label="角色" prop="roles">
          <el-select v-model="adminForm.roles" :disabled="roleDisabled" style="width:100%" multiple placeholder="请选择角色">
            <el-option
              v-for="item in menuRoles"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible=false">{{ $t('permission.cancel') }}</el-button>
        <el-button :loading="button_loging" type="primary" @click="confirmAdmin('ruleForm')">{{ $t('permission.confirm') }}</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import { adminUserList, addAdmin, updateAdmin, deleteAdmin } from '@/api/permission'
import Pagination from '@/components/Pagination'
import { getRoleShow } from '@/api/role'

export default {
  name: 'Admins',
  components: { Pagination },
  data() {
    // 验证密码
    const validatePass = (rule, value, callback) => {
      if (this.dialogType === 'edit') {
        callback()
      } else {
        if (value === '') {
          callback(new Error('密码不能为空'))
        } else {
          if (this.adminForm.password_confirmation !== '') {
            // 对第二个密码框单独验证
            this.$refs.ruleForm.validateField('password_confirmation')
          }
          callback()
        }
      }
    }
    const validatePasswordConfirmation = (rule, value, callback) => {
      if (this.dialogType === 'edit') {
        callback()
      } else {
        if (value === '') {
          callback(new Error('请输入确认密码'))
        } else if (value !== this.adminForm.password) {
          callback(new Error('两次密码输入不正确'))
        } else {
          callback()
        }
      }
    }
    return {
      adminForm: {
        name: '',
        password: '',
        password_confirmation: '',
        loading: false,
        limit: 10,
        page: 1,
        total: 0,
        page_size: [10, 20, 30, 50],
        roles: ''
      },
      // 编辑还是更新
      dialogType: 'edit',
      dialogVisible: false,
      button_loging: false,
      // 超级管理员禁止修改角色
      roleDisabled: false,

      AdminList: [],

      // 角色
      menuRoles: [],

      // 表单验证
      rules: {

        name: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],

        password: [
          { validator: validatePass, trigger: 'blur' }
        ],

        password_confirmation: [
          { validator: validatePasswordConfirmation, trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.getAdminList({ limit: this.adminForm.limit, page: this.adminForm.page })
    getRoleShow().then(res => {
      this.menuRoles = res.data
    })
  },
  methods: {

    getRoleName(params) {
      if (params.length > 0) {
        let role = ''

        for (var i = params.length - 1; i >= 0; i--) {
          role += params[i].name + ','
        }
        return role
      } else {
        return '--'
      }
    },

    // 添加管理员
    handleAddAdmin() {
      this.adminForm.name = ''
      this.adminForm.roles = []
      this.dialogType = 'new'
      this.dialogVisible = true
      this.roleDisabled = false
    },

    // 编辑管理员
    handleEdit(params) {
      const arr = []
      if (params.row.roles !== undefined) {
        for (var i = params.row.roles.length - 1; i >= 0; i--) {
          arr.push(params.row.roles[i].id)
        }
      }
      if (params.row.name === 'admin') {
        this.roleDisabled = true
      } else {
        this.roleDisabled = false
      }

      this.adminForm.name = params.row.name
      this.adminForm.roles = arr
      this.adminForm.password = ''
      this.adminForm.password_confirmation = ''
      this.adminForm.id = params.row.id
      this.dialogType = 'edit'
      this.dialogVisible = true
    },

    // 删除管理员
    handleDelete({ $index, row }) {
      this.$confirm('确定删除么？', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          this.adminForm.loading = true
          await deleteAdmin(row.id).then(res => {
            this.adminForm.loading = false
            this.$notify({
              type: 'success',
              message: '删除成功！'
            })
            this.getAdminList({ limit: this.adminForm.limit, page: this.adminForm.page })
          }).catch(err => {
            this.adminForm.loading = false
          })
        })
    },

    // 确定
    confirmAdmin(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const isEdit = this.dialogType === 'edit'
          if (isEdit) {
            this.button_loging = true
            updateAdmin(this.adminForm).then(res => {
              this.button_loging = false
              this.dialogVisible = false
              this.$notify({
                title: '修改成功！',
                dangerouslyUseHTMLString: true,
                type: 'success'
              })
              this.getAdminList({ limit: this.adminForm.limit, page: this.adminForm.page })
            }).catch(error => {
              this.button_loging = false
            })
          } else {
            this.button_loging = true
            addAdmin(this.adminForm).then(res => {
              this.button_loging = false
              const { name } = this.adminForm
              this.dialogVisible = false
              this.$notify({
                title: '添加成功！',
                dangerouslyUseHTMLString: true,
                message: `
                        <div>用户名: ${name}</div>
                      `,
                type: 'success'
              })
              this.getAdminList({ limit: this.adminForm.limit, page: this.adminForm.page })
            }).catch(error => {
              this.button_loging = false
            })
          }
        } else {
          return false
        }
      })
    },

    // 获取管理员列表
    getAdminList(params) {
      this.adminForm.loading = true
      adminUserList(params).then(res => {
        const data = res.data.data
        this.adminForm.loading = false
        this.AdminList = data.users.data
        this.adminForm.total = data.users.total
        this.adminForm.page = data.users.current_page
      })
    },

    // 更换每页条数
    handleSizeChange(limit) {
      this.adminForm.limit = limit
      this.getAdminList({ limit: this.adminForm.limit, page: this.adminForm.page })
    },

    // 切换分页
    handleCurrentChange(page) {
      this.adminForm.page = page
      this.getAdminList({ limit: this.adminForm.limit, page: this.adminForm.page })
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .roles-table {
    margin-top: 30px;
  }
  .permission-tree {
    margin-bottom: 30px;
  }
}
</style>
